package com.atguigu.product.products.service.impl;

import com.atguigu.product.products.controller.PmsAttrAttrgroupRelationController;
import com.atguigu.product.products.dao.PmsAttrAttrgroupRelationDao;
import com.atguigu.product.products.dao.PmsAttrDao;
import com.atguigu.product.products.entity.PmsAttrAttrgroupRelationEntity;
import com.atguigu.product.products.entity.PmsAttrEntity;
import com.atguigu.product.products.service.PmsAttrService;
import com.atguigu.product.products.vo.respVo.CatelogwithattrRespVo;
import com.atguigu.product.products.vo.respVo.item.SpuItemAttrGroupVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.product.products.dao.PmsAttrGroupDao;
import com.atguigu.product.products.entity.PmsAttrGroupEntity;
import com.atguigu.product.products.service.PmsAttrGroupService;
import org.springframework.transaction.annotation.Transactional;


@Service("pmsAttrGroupService")
public class PmsAttrGroupServiceImpl extends ServiceImpl<PmsAttrGroupDao, PmsAttrGroupEntity> implements PmsAttrGroupService {
    @Autowired
    private PmsAttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private PmsAttrService pmsAttrService;
    @Autowired
    private  PmsAttrGroupDao attrGroupDao;

    @Autowired
    private PmsAttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsAttrGroupEntity> page = this.page(
                new Query<PmsAttrGroupEntity>().getPage(params),
                new QueryWrapper<PmsAttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 根据分类维护id查询分组信息
     *
     * @param params
     * @param categoryId
     * @return
     */
    public PageUtils queryCategoryId(Map<String, Object> params, Long categoryId) {
        Object key = params.get("key");
        if (categoryId == 0) {
            if (key == null) {
                IPage<PmsAttrGroupEntity> page = this.page(
                        new Query<PmsAttrGroupEntity>().getPage(params),
                        new QueryWrapper<PmsAttrGroupEntity>()
                );
                return new PageUtils(page);
            } else {
                QueryWrapper<PmsAttrGroupEntity> queryWrapper = new QueryWrapper();
                queryWrapper.eq("attr_group_id", key).or().like("attr_group_name", key);
                IPage<PmsAttrGroupEntity> page = this.page(
                        new Query<PmsAttrGroupEntity>().getPage(params),
                        queryWrapper
                );
                return new PageUtils(page);
            }

        } else {
            QueryWrapper<PmsAttrGroupEntity> wrapper = new QueryWrapper<PmsAttrGroupEntity>().eq("catelog_id", categoryId);

            if (key == null) {
                IPage<PmsAttrGroupEntity> page = this.page(
                        new Query<PmsAttrGroupEntity>().getPage(params),
                        wrapper
                );
                return new PageUtils(page);
            } else {
                wrapper.and((obj) -> {
                    obj.eq("attr_group_id", key.toString()).or().like("attr_group_name", key.toString());
                });
                IPage<PmsAttrGroupEntity> page = this.page(
                        new Query<PmsAttrGroupEntity>().getPage(params),
                        wrapper
                );
                return new PageUtils(page);
            }
        }
    }

    /**
     * 根据分组id查询关联的属性
     *
     * @param groupId
     * @return
     */
    public List<PmsAttrEntity> attrRelation(Long groupId) {
        List<PmsAttrAttrgroupRelationEntity> pmsAttrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_group_id", groupId));
        if (pmsAttrAttrgroupRelationEntities != null && pmsAttrAttrgroupRelationEntities.size() > 0) {
            List<Long> longs = pmsAttrAttrgroupRelationEntities.stream().map(
                    m -> m.getAttrId()
            ).collect(Collectors.toList());

            //查询对应的属性信息
            List<PmsAttrEntity> pmsAttrEntities = (List<PmsAttrEntity>) pmsAttrService.listByIds(longs);
            return pmsAttrEntities;
        }
       return new ArrayList<>();
    }

    /**
     * 获取属性分组没有关联的其他属性
     * @param params
     * @param groupId
     * @return
     */
    public PageUtils noattrRelation(Map<String, Object> params, Long groupId) {
        IPage<PmsAttrGroupEntity> page = this.page(
                new Query<PmsAttrGroupEntity>().getPage(params),
                new QueryWrapper<PmsAttrGroupEntity>()
        );
        PageUtils utils=new PageUtils(page);
        //根据分组id查询对应的分组id
        PmsAttrGroupEntity group = attrGroupDao.selectOne(new QueryWrapper<PmsAttrGroupEntity>().eq("attr_group_id", groupId));
        if(group!=null){
            //获取分类id,查询次分类下的所有分组
            List<PmsAttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<PmsAttrGroupEntity>().eq("catelog_id", group.getCatelogId()));
            if(groupEntities!=null && groupEntities.size()>0){
                //获取所有分组id
                List<Long> groupIds = groupEntities.stream().map(m -> m.getAttrGroupId()).collect(Collectors.toList());
                //书写sql来获取我们要的属性
               List<PmsAttrEntity> attrEntities =  attrGroupDao.noattrRelation(groupIds,group.getCatelogId());
               if(attrEntities!=null && attrEntities.size()>0){
                   utils.setList(attrEntities);
                   return utils;
               }
            }

        }
        page.setRecords(null);
        return new PageUtils(page);
    }

    /**
     * 分组和属性关联
     * @param entities
     */
    @Transactional
    public void attrRelationDetail(List<PmsAttrAttrgroupRelationEntity> entities) {
        //收集符合条件的关联数据
        List<PmsAttrAttrgroupRelationEntity> entityList=new ArrayList<>();
        //根据属性id查询关联表中是否存在
        entities.forEach((m)->{
            //查询是否存在属性id
            PmsAttrAttrgroupRelationEntity attrId = attrAttrgroupRelationDao.selectOne(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", m.getAttrId()));
            if(attrId!=null){
                attrId.setAttrGroupId(m.getAttrGroupId());
                //修改操作
                attrAttrgroupRelationDao.updateById(attrId);
            }else {
                //新增操作
                entityList.add(m);
            }
        });

        //判断符合条件做批量新增
        if(entityList!=null && entityList.size()>0){
            //批量新增
            attrAttrgroupRelationDao.saveBatch(entityList);
        }
    }

    /**
     * 收集分类下的所有分组和属性值
     * @param catelogId
     * @return
     */
    public List<CatelogwithattrRespVo> catelogIdWithattr(Long catelogId) {
        //查询所有的分组信息
        List<PmsAttrGroupEntity> groupEntities = this.list(new QueryWrapper<PmsAttrGroupEntity>().eq("catelog_id", catelogId));
        if(groupEntities!=null && groupEntities.size()>0){
            List<CatelogwithattrRespVo> catelogwithattrRespVos = groupEntities.stream().map((m) -> {
                CatelogwithattrRespVo respVo = new CatelogwithattrRespVo();
                BeanUtils.copyProperties(m, respVo);
                //根据分组id查询对应的属性id
                List<PmsAttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_group_id", m.getAttrGroupId()));
                if (attrgroupRelationEntities != null && attrgroupRelationEntities.size() > 0) {
                    //收集所有的属性id
                    List<Long> attrIds = attrgroupRelationEntities.stream().map(m1 -> m1.getAttrId()).collect(Collectors.toList());
                    //查询所有对应的属性
                    List<PmsAttrEntity> attrEntities = attrDao.selectList(new QueryWrapper<PmsAttrEntity>().in("attr_id", attrIds));
                    respVo.setAttrs(attrEntities);
                }
                return respVo;
            }).collect(Collectors.toList());
            return catelogwithattrRespVos;
        }
        return null;
    }

    /**
     * 根据spuid以及分类id查询对应的分组和属性信息
     * @param spuId
     * @param catalogId
     * @return
     */
    public List<SpuItemAttrGroupVo> queryGroupWithAttrs(Long spuId, Long catalogId) {
        List<SpuItemAttrGroupVo> spuItemAttrGroupVos =  this.baseMapper.queryGroupWithAttrs(spuId,catalogId);
        if(spuItemAttrGroupVos!=null && spuItemAttrGroupVos.size()>0){
            return spuItemAttrGroupVos;
        }
        return null;
    }

}